package com.open.capacity.reptile.task;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.TypeReference;
import com.open.capacity.finance.dto.OCRData;
import com.open.capacity.reptile.constant.PurchaseNoticeConstant;
import com.open.capacity.reptile.dto.purchase.NoticeResponse;
import com.open.capacity.reptile.service.SourcePurchaseNoticeService;
import com.open.capacity.reptile.util.HttpUtils;
import com.open.capacity.reptile.util.VerifyCodeUtils;
import com.open.capacity.utils.StringUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.http.HttpEntity;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.MessageFormat;
import java.util.*;
import java.util.concurrent.Callable;

@Slf4j
public class SyncPurchaseNoticeRunable implements Callable {

    private SourcePurchaseNoticeService service;

    private volatile Integer currPage;

    private String localFilePath;

    private String verifyCode;


    @Value("${file.uploadpath:/usr/local/files/upload}")
    private String fileuploadPath;

    public SyncPurchaseNoticeRunable(int page, String localFilePath, String verifyCode, SourcePurchaseNoticeService service) {
        this.currPage = page;
        this.localFilePath = localFilePath;
        this.verifyCode = verifyCode;
        this.service = service;
    }

    @Override
    public Object call() throws Exception {
        String url = MessageFormat.format(PurchaseNoticeConstant.requestUrl, currPage, PurchaseNoticeConstant.PAGE_SIZE, verifyCode, URLEncoder.encode(PurchaseNoticeConstant.KEYWORD, "UTF-8"), "");
        String html = HttpUtils.requestGet(url);
        NoticeResponse t = JSONObject.parseObject(html, new TypeReference<NoticeResponse>() {
        });

        if (t != null) {
            log.info(Thread.currentThread().getName() + "：当前页-" + currPage + ",记录数-" + t.getData().size());
            service.save(t.getData());
        }
        return null;
    }
}
